package com.qf.cx.simplenms.webservice.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qf.cx.simplenms.persist.entity.ReaderEntity;
import com.qf.cx.simplenms.persist.service.api.ReaderService;
import com.qf.cx.simplenms.webservice.model.Reader;

@RestController
@RequestMapping(path = "/readers")
public class ReaderController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ReaderService readerService;

	@RequestMapping(method = RequestMethod.GET)
	public List<Reader> getReaders() {
		List<ReaderEntity> readers = readerService.getReaders();
		List<Reader> list = new ArrayList<>();
		readers.forEach(t -> list.add(Reader.from(t)));
		return list;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void addReaders(@RequestBody List<Reader> readers) {
		logger.debug("add readers {}", readers);
		List<ReaderEntity> readerEntities = new ArrayList<>(readers.size());
		readers.forEach(t -> readerEntities.add(t.toReaderEntity()));
		readerService.addReaders(readerEntities);
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.PUT)
	public void updateReader(@PathVariable("name") String name, @RequestBody Reader reader) {
		logger.debug("update readers {}", reader);
		ReaderEntity readerEntity = reader.toReaderEntity();
		readerService.updateReader(readerEntity);
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.DELETE)
	public void deleteReader(@PathVariable("name") String name) {
		logger.debug("delete readers {}", name);
		readerService.deleteReader(name);
	}

}